package server.handler;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

import server.command.ActionCommand;
import server.command.Command;
import server.command.MarkCommand;
import server.server.AndroidServer;

public class CommandReceiver implements Runnable {

	private LinkedBlockingQueue<Command> commands;
	private DataInputStream in;
	private ServerSocket serverSocket;

	public CommandReceiver() throws IOException {
		this.serverSocket = new ServerSocket(12345);
		this.commands = new LinkedBlockingQueue<Command>();
	}

	@Override
	public void run() {
		while (!AndroidServer.isStopped()) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				System.out.println("accept a connection request");
				this.in = new DataInputStream(socket.getInputStream());
			} catch (IOException e2) {
				e2.printStackTrace();
			}
			while (socket != null) {
				try {
					int type = in.readInt();
					if (MarkCommand.isMarkCommand(type)) {
						Command command = new MarkCommand(type, in.readInt(),
								in.readInt(), in.readInt() + 1);
						this.commands.offer(command);
					} else {
						Command command = new ActionCommand(type,
								in.readInt() + 1);
						this.commands.offer(command);
					}
				} catch (IOException e) {
					e.printStackTrace();
					try {
						in.close();
						socket.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					break;
				}
			}
		}
	}

	public LinkedBlockingQueue<Command> getCommands() {
		return this.commands;
	}
}
